/**
 * API响应处理工具函数
 * 统一处理API调用的成功和失败逻辑
 */

import { showToast } from 'vant';
import { Router } from 'vue-router';
import { navigateAfterSubmit } from './navigation';

/**
 * API响应接口定义
 */
export interface ApiResponse<T = any> {
  code: number;
  msg?: string;
  data?: T;
}

/**
 * 表单提交响应数据接口
 */
export interface SubmitResponseData {
  id?: string;
  type?: string;
}

/**
 * 处理表单提交响应
 * @param response API响应
 * @param router Vue Router实例
 * @param successMessage 成功提示消息
 * @param fallbackRoute 备用路由
 * @param delay 延迟时间（毫秒）
 * @returns 是否处理成功
 */
export const handleSubmitResponse = (
  response: ApiResponse<SubmitResponseData>,
  router: Router,
  successMessage: string,
  fallbackRoute?: string,
  delay: number = 1500
): boolean => {
  if (response.code === 0) {
    showToast({ type: 'success', message: response.msg || successMessage });
    navigateAfterSubmit(router, response, fallbackRoute, delay);
    return true;
  } else {
    showToast(response.msg || "提交失败，请重试");
    return false;
  }
};

/**
 * 处理API错误
 * @param error 错误对象
 * @param defaultMessage 默认错误消息
 */
export const handleApiError = (error: any, defaultMessage: string = "操作失败，请重试"): void => {
  console.error('API Error:', error);
  
  let errorMessage = defaultMessage;
  
  // 尝试从错误对象中提取有用的错误信息
  if (error?.response?.data?.msg) {
    errorMessage = error.response.data.msg;
  } else if (error?.message) {
    errorMessage = error.message;
  }
  
  showToast(errorMessage);
};

/**
 * 通用的表单提交处理函数
 * @param submitFn 提交函数
 * @param formData 表单数据
 * @param router Vue Router实例
 * @param successMessage 成功提示消息
 * @param fallbackRoute 备用路由
 * @param setSubmitting 设置提交状态的函数
 * @returns Promise<boolean> 是否提交成功
 */
export const handleFormSubmit = async <T>(
  submitFn: (data: T) => Promise<ApiResponse<SubmitResponseData>>,
  formData: T,
  router: Router,
  successMessage: string,
  fallbackRoute?: string,
  setSubmitting?: (submitting: boolean) => void
): Promise<boolean> => {
  try {
    setSubmitting?.(true);
    
    const response = await submitFn(formData);
    
    return handleSubmitResponse(
      response,
      router,
      successMessage,
      fallbackRoute
    );
  } catch (error) {
    handleApiError(error, "提交失败，请重试");
    return false;
  } finally {
    setSubmitting?.(false);
  }
};

/**
 * 处理详情数据获取响应
 * @param response API响应
 * @param router Vue Router实例
 * @param fallbackRoute 备用路由
 * @returns 详情数据或null
 */
export const handleDetailResponse = <T>(
  response: ApiResponse<T>,
  router: Router,
  fallbackRoute: string = '/'
): T | null => {
  if (response.code === 0 && response.data) {
    return response.data;
  } else {
    showToast(response.msg || "获取详情失败");
    setTimeout(() => {
      router.push(fallbackRoute);
    }, 1500);
    return null;
  }
};

/**
 * 处理审批操作响应
 * @param response API响应
 * @param successMessage 成功提示消息
 * @param onSuccess 成功回调函数
 * @returns 是否操作成功
 */
export const handleApprovalResponse = (
  response: ApiResponse,
  successMessage: string,
  onSuccess?: () => void
): boolean => {
  if (response.code === 0) {
    showToast({ type: 'success', message: response.msg || successMessage });
    onSuccess?.();
    return true;
  } else {
    showToast(response.msg || "操作失败，请重试");
    return false;
  }
};